package com.tom.architect02.ui20.day18;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;

import com.tom.architect02.R;

/**
 * // 1.监听ScrollView 滚动，判断当前滚动的位置跟头部的ImageView 比较，计算背景透明度
 * // 2. 自定义behavior
 */
public class MainActivityUI18 extends AppCompatActivity {
    private View mTitleBar;
    private MyScrollView mScrollView;
    private ImageView mImageView;
    private int mImageHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_ui18);
        StatusBarUtil.setStatusBarTranslucent(this);

        // 进入页面，先设置全透明
        mTitleBar = findViewById(R.id.title_bar);
        mTitleBar.getBackground().setAlpha(0); // 0~255
        mImageView = findViewById(R.id.iv_header);
        mImageView.post(new Runnable() {
            @Override
            public void run() {
                mImageHeight = mImageView.getMeasuredHeight();
            }
        });

        // 不断监听滚动。判断当前滚动的位置与 头部的ImageView比较 计算透明度。
        mScrollView = findViewById(R.id.scroll_view);
        mScrollView.setOnScrollChangeListener(new MyScrollView.ScrollChangeListener() {
            @Override
            public void onScroll(int l, int t, int oldl, int oldt) {
                // 获取图片的高度，根据当前滚动的位置，计算alpha的值。设置给mTitleBar
                // mImageHeight - TitleBar的高度
                float alpha = (float) t / (mImageHeight - dp2px(70));
                if (alpha <= 0) alpha = 0;
                if (alpha > 1) alpha = 1;
                mTitleBar.getBackground().setAlpha((int) (alpha * 255));
            }
        });
    }

    private float dp2px(int dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dp, getResources().getDisplayMetrics());
    }

}
